import React, { RefObject, useEffect, useRef } from "react";
import { initScene, clickRender } from "../utils/viewHelp";
import { Vector2 } from "three";

const Canvas: React.FC = () => {
  const canvasRef: RefObject<HTMLCanvasElement> = useRef(null);
  useEffect(() => {
    initScene(canvasRef);
    console.log('Canvas');
  }, []);

  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement, MouseEvent>) => {
    if (!canvasRef.current) return;
    const rect = canvasRef.current.getBoundingClientRect()
    const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    const y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
    clickRender(new Vector2(x, y));
  }
  return (
    <React.Fragment>
      <div className="w-full">
        <canvas
          ref={canvasRef}
          className="w-full h-full"
          onClick={(e) => handleCanvasClick(e)}
        ></canvas>
      </div>
    </React.Fragment>
  );
};

export default Canvas;
